<template>
	<view class="container">
		<view class="page-body">
			<view class="wrapper">
				<view class="toolbar" @tap="format">
					<view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold"></view>
					<view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti" data-name="italic"></view>
					<view :class="formats.underline ? 'ql-active' : ''" class="iconfont icon-zitixiahuaxian" data-name="underline"></view>
					<view :class="formats.strike ? 'ql-active' : ''" class="iconfont icon-zitishanchuxian" data-name="strike"></view>
					<view :class="formats.align === 'left' ? 'ql-active' : ''" class="iconfont icon-zuoduiqi" data-name="align" data-value="left"></view>
					<view :class="formats.align === 'center' ? 'ql-active' : ''" class="iconfont icon-juzhongduiqi" data-name="align" data-value="center"></view>
					<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi" data-name="align" data-value="right"></view>
					<view :class="formats.align === 'justify' ? 'ql-active' : ''" class="iconfont icon-zuoyouduiqi" data-name="align" data-value="justify"></view>
					<view :class="formats.lineHeight ? 'ql-active' : ''" class="iconfont icon-line-height" data-name="lineHeight" data-value="2"></view>
					<view :class="formats.letterSpacing ? 'ql-active' : ''" class="iconfont icon-Character-Spacing" data-name="letterSpacing" data-value="2em"></view>
					<view :class="formats.marginTop ? 'ql-active' : ''" class="iconfont icon-722bianjiqi_duanqianju" data-name="marginTop" data-value="20px"></view>
					<view :class="formats.previewarginBottom ? 'ql-active' : ''" class="iconfont icon-723bianjiqi_duanhouju" data-name="marginBottom" data-value="20px"></view>
					<view class="iconfont icon-clearedformat" @tap="removeFormat"></view>
					<view :class="formats.fontFamily ? 'ql-active' : ''" class="iconfont icon-font" data-name="fontFamily" data-value="Pacifico"></view>
					<view :class="formats.fontSize === '24px' ? 'ql-active' : ''" class="iconfont icon-fontsize" data-name="fontSize" data-value="24px"></view>

					<view :class="formats.color === '#0000ff' ? 'ql-active' : ''" class="iconfont icon-text_color" data-name="color" data-value="#0000ff"></view>
					<view
						:class="formats.backgroundColor === '#00ff00' ? 'ql-active' : ''"
						class="iconfont icon-fontbgcolor"
						data-name="backgroundColor"
						data-value="#00ff00"
					></view>

					<view class="iconfont icon-date" @tap="insertDate"></view>
					<view class="iconfont icon--checklist" data-name="list" data-value="check"></view>
					<view :class="formats.list === 'ordered' ? 'ql-active' : ''" class="iconfont icon-youxupailie" data-name="list" data-value="ordered"></view>
					<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie" data-name="list" data-value="bullet"></view>
					<view class="iconfont icon-undo" @tap="undo"></view>
					<view class="iconfont icon-redo" @tap="redo"></view>

					<view class="iconfont icon-outdent" data-name="indent" data-value="-1"></view>
					<view class="iconfont icon-indent" data-name="indent" data-value="+1"></view>
					<view class="iconfont icon-fengexian" @tap="insertDivider"></view>
					<view class="iconfont icon-charutupian" @tap="insertImage"></view>
					<view :class="formats.header === 1 ? 'ql-active' : ''" class="iconfont icon-format-header-1" data-name="header" :data-value="1"></view>
					<view :class="formats.script === 'sub' ? 'ql-active' : ''" class="iconfont icon-zitixiabiao" data-name="script" data-value="sub"></view>
					<view :class="formats.script === 'super' ? 'ql-active' : ''" class="iconfont icon-zitishangbiao" data-name="script" data-value="super"></view>
					<view class="iconfont icon-shanchu" @tap="clear"></view>
					<view :class="formats.direction === 'rtl' ? 'ql-active' : ''" class="iconfont icon-direction-rtl" data-name="direction" data-value="rtl"></view>
				</view>

				<editor id="editor" :style="{ paddingTop: toolbarHeiVal + 'px !important' }" class="ql-container" placeholder="开始输入..." showImgSize showImgToolbar showImgResize
				 @statuschange="onStatusChange" :read-only="readOnly" @ready="onEditorReady" @input="changeInput">
				</editor>

			</view>
		</view>

<!-- 		<view class="tui-btn-box">
			<button class="btn-primary" hover-class="btn-hover" @tap="saveAct" type="primary">提交</button>
		</view> -->
		
		<view class="tui-operation">
			<button class="btn-primary tui-btm-small" @tap="saveAct"  hover-class="btn-hover" type="primary">提交</button>
			<!-- <tui-button shape="circle" @tap="saveAct()" class="tui-btm-small">提交</tui-button> -->
		</view>

		<!-- 成功提示框 -->
		<tui-modal :show="modalResult" :custom="true"  @cancel="modalResult=false" :fadein="true">
			<view class="tui-modal-custom">
				<tui-icon name="check" :size="60" color="#19be6b"></tui-icon>
				<view class="tui-modal-custom-text">恭喜您，聚会提交成功</view>
				<tui-button type="primary" shape="circle" @click="toActDetail">去查看</tui-button>
			</view>
		</tui-modal>
	</view>
</template>

<script>
import tuiButton from '@/components/button/button';
import tuiModal from '@/components/modal/modal';
import tuiIcon from '@/components/icon/icon';
export default {
	components: {
		tuiButton,
		tuiModal,
		tuiIcon
	},
	data() {
		return {
			readOnly: false,
			formats: {},
			modalResult: false,
			actId: '',
			// 上传临时变量{metadata:'',upload:''}
			imageTemp: [],
			// 详细描述
			// toobar 高度
			toolbarHeiVal:'',
			// 是否修改
			isEdit:false,
			// 内容是否改变
			contentChange:false
		};
	},
	methods: {
		getHeightVal(){
			let that = this;
			uni.getSystemInfo({
			　　success: function(res) { // res - 各种参数
			　　   console.log(res.windowWidth); // 屏幕的宽度 
			that.toolbarHeiVal=res.windowWidth/2;
			
			　　    /* let info = uni.createSelectorQuery().select(".toolbar-height");
			　　　  　info.boundingClientRect(function(data) { //data - 各种参数
			　　　  　console.log(data.width)  // 获取元素宽度 
					that.toolbarHeiVal=res.windowWidth/2;
					console.log(that.toolbarHeiVal)  // 获取元素宽度
			　　    }).exec()*/
			       }
			});
		},
		changeInput(e){
			this.contentChange=true;
		},
		geActDetail(actId) {
			if(!this.isEdit){
				return;
			}
			let that=this;
			let postData = { actId: actId };
			this.tui
				.request('/api/act/get.short', postData, 'POST', false, true)
				.then(res => {
					if (res.code == 0) {
						// console.log('geActDetail=' + JSON.stringify(res));
						let itemObj  = res.data.act;
						// 从db获取数据显示到页面
						that.editorCtx.setContents({
							delta: JSON.parse(itemObj.deltaObj),
							fail: function(error) {
								console.log(error);
							}
						})
					}else{
						that.tui.toast(res.msg);
					}
				})
				.catch(res => {
					console.log(res);
				});
		},
		readOnlyChange() {
			this.readOnly = !this.readOnly;
		},
		onEditorReady() {
			uni.createSelectorQuery()
				.select('#editor')
				.context(res => {
					this.editorCtx = res.context;
					// 初始化完才赋值
					this.geActDetail(this.actId);
				})
				.exec();
		},
		undo() {
			this.editorCtx.undo();
		},
		redo() {
			this.editorCtx.redo();
		},
		format(e) {
			let { name, value } = e.target.dataset;
			if (!name) return;
			// console.log('format', name, value)
			this.editorCtx.format(name, value);
		},
		onStatusChange(e) {
			const formats = e.detail;
			this.formats = formats;
		},
		insertDivider() {
			this.editorCtx.insertDivider({
				success: function() {
					console.log('insert divider success');
				}
			});
		},
		clear() {
			this.editorCtx.clear({
				success: function(res) {
					console.log('clear success');
				}
			});
		},
		removeFormat() {
			this.editorCtx.removeFormat();
		},
		insertDate() {
			const date = new Date();
			const formatDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
			this.editorCtx.insertText({
				text: formatDate
			});
		},
		insertImage() {
			let that = this;
			uni.chooseImage({
				count: 1,
				success: res => {
					this.editorCtx.insertImage({
						src: res.tempFilePaths[0],
						alt: '图像',
						success: function() {
							console.log('insert image success');
							that.uploadDesc(res.tempFilePaths[0]);
						}
					});
				}
			});
		},
		uploadDesc(file) {
			let that=this;
			this.tui
				.uploadFile('/auth/api/act/uploadDesc', file)
				.then(res => {
					console.log('uploadCoverImg上传结果' + JSON.stringify(res));
					if (res.code == 0) {
						let image={metadata:file,upload:res.data};
						that.imageTemp.push(image);
						console.log("上传图片后"+JSON.stringify(that.imageTemp));
						// this.actFilePath = res.data;
						// return callback(res);
						// this.uploadActGroupImg();
					}
				})
				.catch(res => {
					console.log(res);
				});
		},
		toActDetail() {
			this.modalResult = false;
			uni.navigateTo({
				url: 'act-detail?actId=' + this.actId
			});
		},
		saveBuyEnd(actDesc,deltaObj){
			let actItem={};
			actItem.actId=this.actId;
			actItem.actDesc=actDesc;
			actItem.deltaObj=deltaObj;
			this.tui
				.request('/auth/api/act/update', actItem, 'POST', false, true)
				.then(res => {
					if (res.code == 0) {
						console.log('save' + JSON.stringify(res));
						this.modalResult = true;
					}else{
						this.tui.toast(res.msg);
					}
				})
				.catch(res => {
					console.log(res);
				});
		},
		saveAct() {
			if(!this.contentChange){
				uni.showModal({
				    content: '检测到内容未修改过，是否跳过？',
				    success: (res) => {
				        if (res.confirm) {
							this.toActDetail();
							return;
				        }
				    }
				});
				return;
			};
			let that=this;
			this.editorCtx.getContents({
				success: res => {
					var resStr=JSON.stringify(res);
					console.log('formats:' + resStr);
					for(var i=0;i<that.imageTemp.length;i++){
						resStr=resStr.replace(new RegExp(that.imageTemp[i].metadata,"gm"),that.imageTemp[i].upload);
					}
					// console.log("转换后:"+JSON.stringify((JSON.parse(resStr))));
					let resultObj=JSON.parse(resStr);
					that.saveBuyEnd(resultObj.html,JSON.stringify((resultObj.delta)));
				}
			});
		}
	},
	// 如是新增逻辑，后退怕重复提交新的数据，则新增逻辑后退跳我的发布群列表
	onBackPress(){
		// console.log("back-isEdit="+this.isEdit);
		if (!this.isEdit) {
			uni.navigateBack({
			    delta: 2
			});
		}
	},
	onLoad(e) {
		if (e.actId) {
			this.actId = e.actId;
		}
		uni.loadFontFace({
			family: 'Pacifico',
			source: 'url("https://sungd.github.io/Pacifico.ttf")'
		});

		// 如是编辑模式，则获取DB内容
		if (e.type=='edit') {
			this.isEdit=true;
		}
		this.getHeightVal();
	}
};
</script>

<style>
@import '../../static/style/editor-icon.css';

	.wrapper {
		/* padding: 5px; */
	}

	.iconfont {
		display: inline-block;
		padding: 8px 8px;
		width: 24px;
		height: 24px;
		cursor: pointer;
		font-size: 20px;
	}

	.toolbar {
		box-sizing: border-box;
		border-bottom: 0;
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
		/* background-color:#D5D5D6; */
		position: fixed;
		z-index: 997;
		background-color: #eee;
	}


	.ql-container {
		box-sizing: border-box;
		padding: 14px 30px 14px 6px;
		width: 100%;
		min-height: 30vh;
		height: auto;
		background: #fff;
		/* margin-top: 10px; */
		font-size: 16px;
		line-height: 1.5;
		margin-bottom: 130rpx;
		/* padding-top: var(--window-top) !important; */
	}
	.ql-container .ql-editor{
		/* background-color: #007AFF !important; */
	}

	.ql-active {
		color: #06c;
	}
	.tui-btn-box {
		padding: 40rpx 20rpx;
		margin: 20rpx;
		box-sizing: border-box;
	}
	.tui-modal-custom {
		text-align: center;
	}
	
	.tui-tips-img {
		width: 100rpx;
		height: 100rpx;
		margin-top: 20rpx;
	}
	
	.tui-modal-custom-text {
		font-size: 30rpx;
		color: #333;
		padding: 30rpx 0;
	}
	/* tui-operation */
	.tui-operation {
		width: 100%;
		height: 120rpx;
		overflow: hidden;
		background: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 99999;
		/* padding-bottom: 10rpx; */
		/* padding-bottom: env(safe-area-inset-bottom); */
	}
	.tui-btm-small {
		/* height: 70rpx; */
		margin: 30rpx 30rpx 30rpx 30rpx;
		/* width: 50%; */
		/* font-size: 24rpx; */
		/* line-height: 70rpx; */
	}
</style>
